package com.finance.cooperate.common.utils;

import java.util.Arrays;
import java.util.Random;

/**
 * @ClassName ProbabilityUtils
 * @Description 随机概率值计算
 * @Author shen
 * @Date 2022/6/20 22:31
 * @Modify ...
 */
public final class ProbabilityUtils {

    /**
     * 是否命中
     * @param weight 权重
     * @param seed 种子值
     * @return
     */
    public static boolean isHit(double weight, Long seed) {

        Random random = new Random(seed);

        int nextInt = random.nextInt(100);
        nextInt += 1;

        if (nextInt <= weight) {
            return true;
        }

        return false;
    }

    /**
     * 选择index
     * @param weights 各项权重
     * @param seed 种子值
     * @return
     */
    public static int shuntSelection(double[] weights,  Long seed) {

        Double sumWeight = Arrays.stream(weights).sum();

        Random random = new Random(seed);

        int nextInt = random.nextInt(sumWeight.intValue());
        nextInt += 1;

        double tempWeight = 0;
        for (int i = 0; i < weights.length; i++) {

            if (nextInt > tempWeight && nextInt <= tempWeight + weights[i]) {
                //命中
                return i;
            }

            tempWeight += weights[i];

        }

        return 0;
    }

}
